<?php
/**
 * DB.php		
 *
 * @package		
 * @Copyright	(c) All rights reserved
 * @Author		skyCrack <skyCrack@126.com>
 * @Version		$Id$
 */

abstract class DB {
	public static function factory($driver = 'mysql', $options = array()) {
		$className	=	'DB_Adapter_' . ucfirst($driver);
		
		require_once(str_replace('_', '/', $className) . '.php');
		$obj = new $className($options);

		return $obj;
	}
	
	public static function singleton($options = array(), $hash = null) {
		static $instances;
		if ( is_string($options) ) {
			$platform	=	$options;
			$options	=	compact('platform');
		}
		$driver			=	( isset($options['driver']) ) ? $options['driver'] : 'mysql';
		$index			=	( isset($options['platform']) ) ? $options['platform'] : $driver;
		$options		=	array_merge(self::_getConfig($index), $options);
		
		//need to hash
		if ( isset($options['hosts']) ) {
			if ( null === $hash ) {
				$hash = self::_getDefaultHash($options['hosts']);
			}
			$hashResult			=	$hash->hash();
			$options['host']	=	$options['hosts'][$hashResult['hash']];
			unset($options['hosts']);
		}
		
		$key = self::_makeKey(array_merge($options, array('driver'	=>	$driver)));
		
		if ( !isset($instances[$key]) ) {
			$instances[$key]	=	self::factory($driver, $options);
		}
		
		return $instances[$key];
	}
	
	private static function _makeKey($options) {
		ksort($options);
		return md5(serialize($options));
	}
	
	private static function _getConfig($index) {
		$index		=	'_' . ucfirst($index) . 'Configure';
		if ( isset($GLOBALS[$index]) ) {
			return $GLOBALS[$index];
		} else {
			return array();
		}
	}
	
	private static function _getDefaultHash($options) {
		require_once 'Hash/Random.php';
		
		return new Hash_Random($options);
	}
}
?>